package com.shopping.huaju.commodity.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.shopping.huaju.commodity.entity.*;
import com.shopping.huaju.commodity.entity.vo.*;
import com.shopping.huaju.commodity.feign.CouponFeignService;
import com.shopping.huaju.commodity.feign.SearchFeignService;
import com.shopping.huaju.commodity.feign.WareFeignService;
import com.shopping.huaju.commodity.service.*;
import com.shopping.huaju.commodity.entity.vo.SkuHasStockVo;
import com.shopping.huaju.common.constant.ProductConstant;
import com.shopping.huaju.common.to.SkuReductionTo;
import com.shopping.huaju.common.to.SpuBoundTo;
import com.shopping.huaju.common.to.es.SkuEsModel;
import com.shopping.huaju.common.utils.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shopping.huaju.common.utils.PageUtils;
import com.shopping.huaju.common.utils.Query;

import com.shopping.huaju.commodity.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Resource
    private SpuInfoDescService spuInfoDescService;
    @Resource
    private SpuImagesService spuImagesService;
    @Resource
    private ProductAttrValueService productAttrValueService;
    @Resource
    private SkuImagesService skuImagesService;

    @Resource
    private SkuInfoService skuInfoService;
    @Resource
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Resource
    private CouponFeignService couponFeignService;

    @Resource
    private BrandService brandService;

    @Resource
    private CategoryService categoryService;
    @Resource
    private AttrService attrService;
    @Resource
    private WareFeignService wareFeignService;
    @Resource
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    //自定义接口，根据传入的SPU完整信息 保存入库SPU完整信息
    //该方法需要操作多张表，需要开启声明式事务
    @Override
    @Transactional
    public boolean saveSpuInfo(SpuSaveVO saveVO) {
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        //将 saveVO中对应的属性字段值赋给 spuInfoEntity
        BeanUtils.copyProperties(saveVO, spuInfoEntity);
        //添加创建SPU时间和更新时间
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        //将 SPU的基本信息保存入库
        this.saveSpuBaseInfo(spuInfoEntity);

        //将 SPU的 介绍图片信息入库
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        //SpuSaveVO中是没有id的 spuId是保存创建spuInfoEntity自增长回填的id
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        List<String> decript = saveVO.getDecript();
        if (decript.isEmpty()) { //如果 没有上次介绍图片，则需要给一个默认显示的图片
            String defaultPhoto = "default.jpg";
            spuInfoDescEntity.setDecript(defaultPhoto);
        } else { //如果有一张，或多张图片，需要以url,间隔的形式保存到数据库
            //["1.jpg","2.jpg"] -> "1.jpg,2.jpg"
            spuInfoDescEntity.setDecript(String.join(",", decript));
        }
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        //将 SPU的 展示图片信息入库
        spuImagesService.saveImages(spuInfoEntity.getId(), saveVO.getImages());

        //将 SPU的 基本属性入库
        productAttrValueService.saveBaseAttrs(spuInfoEntity.getId(), saveVO.getBaseAttrs());

        //将 SKU的 基本信息入库
        List<Skus> skus = saveVO.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(sku -> {
                System.out.println("===========");
                System.out.println(sku);
                //封装 SkuInfoEntity属性 为集合
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setBrandId(saveVO.getBrandId());
                skuInfoEntity.setCatalogId(saveVO.getCatalogId());
                skuInfoEntity.setCountstatus(sku.getCountStatus());
                skuInfoEntity.setDiscount(sku.getDiscount());
                skuInfoEntity.setFullcount(sku.getFullCount());
                skuInfoEntity.setFullprice(sku.getFullPrice());
                skuInfoEntity.setPrice(sku.getPrice());
                skuInfoEntity.setPricestatus(sku.getPriceStatus());
                skuInfoEntity.setReduceprice(sku.getReducePrice());
                skuInfoEntity.setSkuDesc(null);
                skuInfoEntity.setSkuName(sku.getSkuName());
                skuInfoEntity.setSkuSubtitle(sku.getSkuSubtitle());
                skuInfoEntity.setSkuTitle(sku.getSkuTitle());
                List<Images> images = sku.getImages();
                if (images != null) {
                    List<Images> collect = images.stream().filter(image -> image.getDefaultImg() == 1).collect(Collectors.toList());
                    int count = collect.size();
                    if (count < 1) {
                        skuInfoEntity.setSkuDefaultImg("defaultPhoto.jpg");
                    } else {
                        skuInfoEntity.setSkuDefaultImg(collect.get(0).getImgUrl());
                    }
                }
                skuInfoService.saveSkuBaseInfos(skuInfoEntity);

                // 将 Sku 的 图片信息入库
                if (images != null && !images.isEmpty()) {    //如果对应的 sku 信息上传了图片，则需要对图片信息进行保存
                    List<SkuImagesEntity> skuImagesEntities = images.stream()
                            .filter(image -> StringUtils.isNotBlank(image.getImgUrl()))
                            .map(image -> {
                                SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                                skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                                skuImagesEntity.setDefaultImg(image.getDefaultImg());
                                skuImagesEntity.setImgUrl(image.getImgUrl());
                                skuImagesEntity.setImgSort(0);
                                return skuImagesEntity;
                            }).collect(Collectors.toList());
                    skuImagesService.saveBatch(skuImagesEntities);
                }

                //将 Sku 的销售属性值 入库
                List<Attr> attrs = sku.getAttr();
                if (attrs != null && !attrs.isEmpty()) {
                    List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attrs.stream().map(attr -> {
                        SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                        skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                        skuSaleAttrValueEntity.setAttrName(attr.getAttrName());
                        skuSaleAttrValueEntity.setAttrSort(0);   //排序优先级默认为0
                        skuSaleAttrValueEntity.setAttrId(attr.getAttrId());
                        skuSaleAttrValueEntity.setAttrValue(attr.getAttrValue());
                        return skuSaleAttrValueEntity;
                    }).collect(Collectors.toList());
                    //批量保存 销售属性 信息
                    skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
                }

                // 将对于销售商品奖励的金币和成长值数据入库
                SpuBoundTo spuBoundTo = new SpuBoundTo();
                spuBoundTo.setSpuId(spuInfoEntity.getId());
                Bounds bounds = saveVO.getBounds();
                BeanUtils.copyProperties(bounds,spuBoundTo);
                //封装完毕后进行远程调用。
                R boundSaveRes = couponFeignService.saveSpusBound(spuBoundTo);
                if((Integer) boundSaveRes.get("code") != 0){
                    log.error("保存商品奖励积分信息出错！");
                }
                System.out.println(sku);
                // 将Sku中商品满减、和折扣的数据入库
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setFullCount(sku.getFullCount().intValue());
                skuReductionTo.setSkuId(skuInfoEntity.getSkuId());
                if(skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R skuReductionRes = couponFeignService.saveSkuReduction(skuReductionTo);
                    if ((Integer) skuReductionRes.get("code") != 0) {
                        log.error("保存商品折扣满减信息出错！");
                    }
                }
            });
        }
        return true;
    }
    // 实现 SpuInfoEntity 对象 带条件分页查询
    @Override
    public PageUtils queryPageByConditions(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        //如果存在检索条件(id匹配或name模糊查询)则加入到查询条件中
        if(StringUtils.isNotBlank(key)){
            queryWrapper.and(wrapper->{
                wrapper.eq("id",key).or().like("spu_name",key);
            });
        }
        // 如果存在分类查询条件,并且分类id不为零(默认传的是0）则添加到查询条件中
        String catalogId = (String)params.get("catalogId");
        if(StringUtils.isNotBlank(catalogId) && !"0".equals(catalogId)){
            queryWrapper.eq("catalog_id",catalogId);
        }
        //如果存在品牌查询条件，而且品牌id不为0(默认传的是0) 则添加到查询条件中去
        String brandId = (String) params.get("brandId");
        if(StringUtils.isNotBlank(brandId) && !"0".equals(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }
        //如果携带商品发布状态条件，状态条件不为空或"  "，则添加到查询条件中去
        String status = (String) params.get("status");
        if(StringUtils.isNotBlank(status)){
            queryWrapper.eq("publish_status",status);
        }
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }
    //修改商品发布状态为 上架状态
    @Override
    public void updatePublishStatusUp(Long spuId) {
        //1、查出当前spuId对应的所有sku信息,品牌的名字
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);

        //TODO 4、查出当前sku的所有可以被用来检索的规格属性,sku的规格都是一样的 因此只需要获取一次
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrlistforspu(spuId);

        List<Long> attrIds = baseAttrs.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        List<Long> searchAttrIds = attrService.selectSearchAttrIds(attrIds);
        //转换为Set集合
        Set<Long> idSet = searchAttrIds.stream().collect(Collectors.toSet());

        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());

        List<Long> skuIdList = skuInfoEntities.stream()
                .map(SkuInfoEntity::getSkuId)
                .collect(Collectors.toList());
        //TODO 1、发送远程调用，库存系统查询是否有库存
        Map<Long, Boolean> stockMap = null;
        try {
            R skuHasStock = wareFeignService.getSkuHasStock(skuIdList);
            //
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {};
            stockMap = skuHasStock.getData(typeReference).stream()
                    .collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务查询异常：原因{}",e);
        }

        //2、封装每个sku的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> collect = skuInfoEntities.stream().map(sku -> {
            //组装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku,esModel);
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());

            //设置库存信息
            if (finalStockMap == null) {
                esModel.setHasStock(true);
            } else {
                esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }

            //TODO 2、热度评分。0
            esModel.setHotScore(0L);

            //TODO 3、查询品牌和分类的名字信息
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            esModel.setBrandName(brandEntity.getName());
            //esModel.setBrandId(brandEntity.getBrandId());
            esModel.setBrandImg(brandEntity.getLogo());

            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            //esModel.setCatalogId(categoryEntity.getCatId());
            esModel.setCatalogName(categoryEntity.getName());

            //设置检索属性
            esModel.setAttrs(attrsList);

            return esModel;
        }).collect(Collectors.toList());

        //TODO 5、将数据发给es进行保存：huaju-search
        R r = searchFeignService.productStatusUp(collect);

        if (r.getCode() == 0) {
            //远程调用成功
            //TODO 6、修改当前spu的状态
            this.baseMapper.updaSpuStatus(spuId, ProductConstant.ProductStatusEnum.SPU_UP.getCode());
        } else {
            //远程调用失败
            //TODO 7、重复调用？接口幂等性:重试机制
        }
    }
    //修改商品发布状态为 下架状态
    @Override
    public void updatePublishStatusDown(Long spuId) {
        this.baseMapper.updatePublishStatus(spuId,2);
    }

    /**
     * 根据skuId查询spu的信息
     * @param skuId
     * @return
     */
    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {

        //先查询sku表里的数据
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);

        //获得spuId
        Long spuId = skuInfoEntity.getSpuId();

        //再通过spuId查询spuInfo信息表里的数据
        SpuInfoEntity spuInfoEntity = this.baseMapper.selectById(spuId);

        //查询品牌表的数据获取品牌名
        BrandEntity brandEntity = brandService.getById(spuInfoEntity.getBrandId());
        spuInfoEntity.setBrandName(brandEntity.getName());

        return spuInfoEntity;
    }

    private boolean saveSpuBaseInfo(SpuInfoEntity spuInfoEntity) {
        return this.save(spuInfoEntity);
    }

}